package com.hehe.controller.Photo;

import com.hehe.Common.Upload_images;
import com.hehe.POJO.Photo;
import com.hehe.POJO.Qq_space;
import com.hehe.POJO.User;
import com.hehe.Repository.CollectRepository;
import com.hehe.Repository.PhotoRepository;
import com.hehe.Repository.UserRepository;
import com.hehe.Service.CollectService;
import com.hehe.Service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Objects;
import java.util.Optional;

import static java.awt.SystemColor.text;

@Slf4j
@Controller
public class PhotoAdd {


    @Value("${config_file_name}")
    private String config_file_name;

    @Value("${file.upload.path}")
    private String SAVE_FOLDER_PATH;


    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private UserRepository userRepository;

    @Resource
    private UserService userService;

    @Resource
    private CollectService collectService;

    @Resource
    private PhotoRepository photoRepository;

    @Resource
    private CollectRepository collectRepository;


    @GetMapping("/photo-add")
    public String photo_detail(HttpServletRequest request, Model model) {
        String usernameByCookie = userService.get_username_by_cookie(request);
        User user = userRepository.findByUsername(usernameByCookie);
        if (Objects.equals(user.getRole(), "admin")) {
            return "photo/photo-add.html";
        }
        return "index.html";
    }





    @PostMapping("/photo-add/upload")
    public ResponseEntity<?> handleFileUpload(
            HttpServletRequest request,
            @RequestParam("title") String title,
            @RequestParam("description") String description,
            @RequestParam("files") MultipartFile[] files) {

        System.out.println("Received text: " + title);
        System.out.println("Received text: " + description);

        if (files.length == 0) {
            return ResponseEntity.ok("No files uploaded.");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String timestamp = sdf.format(new Date());
        System.out.println(timestamp);               //  20240714073648

        String father_foler = "Photo/" + timestamp + "/";  // 文件夹

        ArrayList<String> filePathList = Upload_images.saveImagesWithWatermarkandCompress(SAVE_FOLDER_PATH + father_foler, files, 100, "AAAbbb233.com");

        if (filePathList == null) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred while saving files.");
        }

        StringBuilder filePaths_str = new StringBuilder();
        // 遍历 filePathList
        // ResourceConfig 配置映射路径 images
        for (String filePath : filePathList) {
//           访问全路径  http://192.168.8.194:8055/images/b4852718-f57e-474f-af37-fe5aad03d973.jpg
//            String file_URL = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/images/" + filePath;
//            System.out.println("file_URL = " + file_URL);
            String full_path = father_foler + filePath;
            System.out.println("full_path = " + full_path);
            filePaths_str.insert(0, full_path + ",");
        }
        Photo photo = new Photo();
        photo.setTitle(title);
        photo.setDescription(description);
        photo.setImgPath(filePaths_str.toString());
        photo.setPrice(BigDecimal.valueOf(0.98));
        photoRepository.save(photo);
        return ResponseEntity.ok(filePathList);
    }




////    @ModelAttribute("loggedInUser")
////    public Tb_user getLoggedInUser(@CookieValue(value = "username", required = false) String username) {
////        if (username != null) {
////            // Simulate fetching user data from a service or database
////            Tb_user tb_user = new Tb_user();
////            tb_user.setUsername(username);
////            return tb_user;
////        }
////        return null;
////    }
//
//
//    @PostMapping("/login")
//    public String login(@RequestParam String username, @RequestParam String password, HttpServletResponse response, Model model) {
//        User tb_user = userRepository.findByUsername(username);
//        if (tb_user != null && passwordEncoder.matches(password, tb_user.getPassword())) { // 使用 BCrypt 验证密码
//            Cookie cookie = new Cookie("username", tb_user.getUsername());
//            cookie.setMaxAge(15 * 24 * 60 * 60); // 15 days
//            response.addCookie(cookie);
//            return "redirect:/login-success";
//        }
//        model.addAttribute("error", "用户名 或 密码 错误");
//        return "login/login.html";
//    }
//
//
//    @GetMapping("/login-success")
//    public String homePage(HttpServletRequest request) {
////        Cookie[] cookies = request.getCookies();
////        if (cookies != null) {
////            for (Cookie cookie : cookies) {
////                if ("username".equals(cookie.getName())) {
////                    System.out.println("用户已登录，继续处理请求");
////                    return "login-success.html";
////                }
////            }
////        }
////        return "login.html";
//        return "login/login-success.html";
//    }
//
//
//    @GetMapping("/logout")
//    public String logout(HttpServletRequest request, HttpServletResponse response) {
//        Cookie[] cookies = request.getCookies();
//        if (cookies != null) {
//            for (Cookie cookie : cookies) {
//                if ("username".equals(cookie.getName())) {
//                    cookie.setValue(null);
//                    cookie.setMaxAge(0);
//                    response.addCookie(cookie);
//                }
//            }
//        }
//        return "redirect:/";
//    }





}



